package wechat

import (
	"fmt"
	"gitee.com/edodo/flysdk/api"

	"github.com/jinzhu/copier"
)

const (
	API_HOST                = "https://api.weixin.qq.com"
	ACCESS_TOKEN_URL        = API_HOST + "/cgi-bin/token"
	STABLE_ACCESS_TOKEN_URL = API_HOST + "/cgi-bin/stable_token"

	JSCODE_SESSION_URL   = API_HOST + "/sns/jscode2session"
	GET_PHONE_NUMBER_URL = API_HOST + "/wxa/business/getuserphonenumber"

	CLEAR_QUOTA_URL   = API_HOST + "/cgi-bin/clear_quota"
	GET_API_QUOTA_URL = API_HOST + "/cgi-bin/openapi/quota/get"
)

type WxError struct {
	ErrCode int    `json:"errcode"`
	ErrMsg  string `json:"errmsg"`
}

type WxAccessToken struct {
	WxError
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"` //凭证有效时间，单位：秒。目前是7200秒之内的值。
}

type WxCode2Session struct {
	WxError
	*api.Code2Session
}

type WxPhoneNumber struct {
	WxError
	PhoneInfo *api.PhoneNumber `json:"phone_info"`
}

type WxQuota struct {
	WxError
	Quota api.Quota `json:"quota"`
}

func (we WxError) IsOk() bool {
	return we.ErrCode == 0
}

func (we WxError) Err() error {
	return fmt.Errorf("err_code=%d, err_msg=%s", we.ErrCode, we.ErrMsg)
}

func (wat WxAccessToken) ToAccessToken() (at *api.AccessToken, e error) {
	if !wat.IsOk() {
		e = wat.Err()
		//glog.Errorf("Get access token failed: %v", e)
		return
	}
	at = new(api.AccessToken)
	copier.Copy(at, wat)
	at.Calc()
	return
}
